import React from "react";
const CounterContext = React.createContext()

function reducer(state = {number: 0}, action) {
  switch (action.type) {
    case 'add':
      return {number: state.number + 1}
    case 'del':
      return {number: state.number - 1}
    default:
      return state
  }
}

function Counter() {
  const {state, dispatch} = React.useContext(CounterContext)
  return (
    <div>
      <h1>{state.number}</h1>
      <button onClick={() => dispatch({type: 'add'})}>+</button>
      <button onClick={() => dispatch({type: 'del'})}>-</button>
    </div>
  )
}

function App() {
  const [state, dispatch] = React.useReducer(reducer, {number: 0})
  return (
    <CounterContext.Provider value={{state, dispatch}}>
      <Counter />
    </CounterContext.Provider>
  )
}

export default App
